<?php //pack11class

class ObjectsManager {
    
    private static $objectsDone=false;
    public static $objects=array();
    public static $objectsByID=array();

    public static $usedProperties=array();
    public static $sortable=array();

    public static $showPrice="undefined";

    public static function getObject($id){
        if(!self::$objectsDone) self::getObjects();
//        /print_r(self::$objectsByID);
        if(array_key_exists($id, self::$objectsByID)) return self::$objectsByID[$id];
        return false;
    }

    public static function getObjects($showAll=false,$inactive=false,$no_limit=false) {
        array_push(Tracer::$traceFrom,"ObjectsManager");
        if(self::$objectsDone) return self::$objects;

        $sqlArray=array();
        $specialField=", IFNULL(`spec`,100) ASC";

        foreach(PropertiesManager::properties() as $property) {
            //if($property->system=="special") $specialField=", ".$property->field;
            if(isset($property->value)) {
                if($property->value!=0) {
                    array_push($sqlArray,"`{$property->field}`='{$property->value}'");
                }
            }
        }
        
        $whereString=($showAll)? "where `time`>=date_sub(curdate(), interval 1 month) or `active`='1'":(($inactive)?"":"where `active`='1'");
        $navigation=SettingsManager::getSetting("navigation");
        $useObjects=SettingsManager::getSetting("objects");
        $useObjects->value=false;
        if($navigation) $useObjects->value=false;

        $sortby=SettingsManager::getSetting("sortby");
        $desc=SettingsManager::getSetting("desc");
        $sortByString="";
        if($sortby->value) {
            $sortByProperty=PropertiesManager::getProperty($sortby->value);
            $descString=($desc->value)? " DESC": " ASC";
            $descNumber=($desc->value)? 0: 999999999999;
            $sortByString=" order by `".$sortByProperty->field."` ".$descString;
        }

//        $whereString.=" AND ".implode(" AND ",$sqlArray);
//        if(SearchManager::$extraWhere) $whereString.=" AND ".SearchManager::$extraWhere;

        if((count($sqlArray)>0)) {
            $whereString.=" AND ".implode(" AND ",$sqlArray);
        }
        if(SearchManager::$extraWhere) $whereString.=" AND ".SearchManager::$extraWhere;
        if($sortby->value) $whereSortString1=(strlen($whereString)>0)? " AND `".$sortByProperty->field."` is not null":" where `".$sortByProperty->field."` is not null";
        if($sortby->value) $whereSortString2=(strlen($whereString)>0)? " AND `".$sortByProperty->field."` is null":" where `".$sortByProperty->field."` is null";
        $limit=($no_limit)? "":" limit ".(ObjectsListNavigation::getPageNumber()-1)*ObjectsListNavigation::getCount().",".ObjectsListNavigation::getCount();
        if($sortby->value) {
            $query="Select SQL_CALC_FOUND_ROWS ".MySQL::TABLE_OBJECTS.".*,`d12_specials`.`priority` as `spec` from ".MySQL::TABLE_OBJECTS." left join `d12_specials` on (".MySQL::TABLE_OBJECTS.".`prop43`=`d12_specials`.`id`)".$whereString." order by IFNULL(`".$sortByProperty->field."`,".$descNumber.")".$descString.", active DESC{$specialField}, time DESC".$limit.";";
            //$query="(Select SQL_CALC_FOUND_ROWS * from ".MySQL::TABLE_OBJECTS.$whereString.$whereSortString1.$sortByString.") union (Select * from ".MySQL::TABLE_OBJECTS.$whereString.$whereSortString2." order by `special`) limit ".(ObjectsListNavigation::getPageNumber()-1)*ObjectsListNavigation::getCount().",".ObjectsListNavigation::getCount().";";
        } else {
            $query="Select SQL_CALC_FOUND_ROWS ".MySQL::TABLE_OBJECTS.".*,`d12_specials`.`priority` as `spec` from ".MySQL::TABLE_OBJECTS." left join `d12_specials` on (".MySQL::TABLE_OBJECTS.".`prop43`=`d12_specials`.`id`)".$whereString." order by active DESC{$specialField}, time DESC".$limit.";";
            trace($query);
        }

        $objects=self::loadData($query);
        

        return $objects;
    }

    private static function loadData($query) {
        $sql=MySQLGet::process($query);
        //trace(MySQLGet::getQuery());
        $total=MySQLGet::process("Select FOUND_ROWS() as `count`;");
        ObjectsListNavigation::setObjectsCount($total[0]["count"]);

        if(!$sql) return false;

        foreach($sql as $row) {
            $_object=new DekaroObject;
            $_object->id=$row["id"];
            //$_object->special=$row["special"];
            $_object->active=($row["active"])? true:false;
            $_object->mapdata=str_replace(array("(",")"),"",$row["map"]);
            $languages=LanguagesManager::getLanguages();
            $_object->description=array();
            foreach($languages as $language) {
                $_object->description[$language->id]=(array_key_exists("text".$language->id, $row))? stripslashes($row["text".$language->id]):"";
            }
            foreach(PropertiesManager::properties() as $property) {
                //trace("---------------".$property->field." ".$row[$property->field]);
                if(!is_null($row[$property->field])){
                    self::$usedProperties[$property->system]=$property;
                    if($property->sortable) self::$sortable[$property->system]=$property;
                    $name=$property->system;
                    $_object->$name=$row[$property->field];
                    //if($property->system=="special") trace("::::::".$_object->special);
                }
            }
            //trace("=======================");
            $_object->finalizeProperties();
            array_push(self::$objects,$_object);
            self::$objectsByID[$_object->id]=$_object;
        }
        //usort(self::$objects, array(__CLASS__,"sortObjects"));
        self::$objectsDone=true;
        return self::$objects;
    }

    public static function sortObjects(DekaroObject $a,DekaroObject $b) {
        $setting=SettingsManager::getSetting("sortby");
        if($setting->value) {

            $descSetting=SettingsManager::getSetting("desc");
            $desc=($descSetting->value)? true:false;

            $sortBySetting=PropertiesManager::getProperty($setting->value);
            $aProperties=$a->usedProperties();
            $bProperties=$b->usedProperties();

            if(!array_key_exists($sortBySetting->system, $aProperties)) return true;
            if(!array_key_exists($sortBySetting->system, $bProperties)) return false;
            $aProperty=$aProperties[$sortBySetting->system];
            $bProperty=$bProperties[$sortBySetting->system];
            
            //trace($aProperty." ".$bProperty);
            if($sortBySetting->isValue) {
                if($desc) {
                    return $aProperty->value<=$bProperty->value;
                } else {
                    return $aProperty->value>=$bProperty->value;
                }
            } else if ($sortBySetting->hasValue) {
                if($desc) {
                    return $aProperty->value<=$bProperty->value;
                } else {
                    return $aProperty->value>=$bProperty->value;
                }
            }
        } else {
            return !$a->special;
        }
    }

    public static function getShowPrice() {
        if(self::$showPrice=="undefined") {
            self::$showPrice=SettingsManager::getSetting("showPrice")->value;
        }
        return (self::$showPrice)? true:false;
    }

    private static function setCurrentObjectsList($s) {
        $objects=explode(",",$s);
        $result=array();
        foreach($objects as $id){
            array_push($result,"`id`='".$id."'");
        }
        return "(".implode(" OR ", $result).")";
    }

    public static function getCurrentObject($id=0) {

        if($id==0) {
            $objectID=SettingsManager::getSetting("object")->value;
            if(!$objectID) return;
        } else {
            $objectID=$id;
        }

        if(!self::$objectsDone) {
            $query="Select * from ".MySQL::TABLE_OBJECTS." where `id`='$objectID' limit 1;";
            $objects=self::loadData($query);
            self::$objectsDone=true;
        }

        $object=self::getObject($objectID);
        $object->getLabel(true);

        /*$properties=$object->usedProperties();
        $propertiesArray=array();
        foreach($properties as $property) {
            $rootProperty=PropertiesManager::getProperty($property->id);
            foreach($rootProperty as $prop=>$is) $rootProperty->$prop=$property->$prop;
            if(!$property->combined && $property->group=="address") {
                array_push($propertiesArray,$property->string);
            }
        }
        $object->label=implode(", ",$propertiesArray);*/
        //$object->finalizeProperties();

        return $object;
    }

    public static function saveObject() {
        array_push(Tracer::$traceFrom,__CLASS__);
        $object=SettingsManager::getSetting("object");
        if(is_numeric($object->value)) {
           $id=$object->value;
        } else {
            return;
        }
        $columnsData=MySQLGet::process("SHOW COLUMNS FROM ".MySQL::TABLE_OBJECTS);
        $columns=array();
        $nulls=array();
        $fields=array();

        foreach($columnsData as $row) {
            //trace("[[[[[[[[[[]]]]]]]]]]".$row["Field"]);
            $columns[$row["Field"]]=$row["Field"];
            $nulls[$row["Field"]]=($row["Null"]=="YES")? true:false;
        }
        $used=array();
        foreach($_POST as $name=>$value) {
            $property=PropertiesManager::getProperty($name);
            $field=($property)? $property->field:$name;
            //trace($field." ".$value);
            if(array_key_exists($field, $columns)) {
                $used[$field]="used";
                if(strlen($value)>0){
                    if($value==0 && strlen($value)==1) {
                        array_push($fields, "`".$field."`=NULL");
                    } else {
                        array_push($fields, "`".$field."`='".htmlspecialchars($value)."'");
                    }
                } else {
                        array_push($fields, "`".$field."`=NULL");
                }
            }
        }
        foreach(PropertiesManager::properties() as $property) {
            if(!array_key_exists($property->field, $used)) {
                if(array_key_exists($property->field, $nulls)) {
                    $nullValue=($nulls[$property->field])? "NULL":"'1'";
                    array_push($fields, "`".$property->field."`=".$nullValue);
                }
            }
        }
        $query="Update ".MySQL::TABLE_OBJECTS." set ".implode(", ", $fields)." where `id`=".$id.";";
        trace($query);
        MySQLSet::process($query);
    }

}
?>
